package com.fessc.develop.handler;

import com.fessc.develop.entity.comvo.BankCheckFileDownVo;
import com.fessc.develop.entity.dbvo.TCheckResult;
import com.fessc.develop.exception.BusinessException;
import com.fessc.develop.handler.processor.send.ISendProcessor;
import com.fessc.develop.model.enums.EnumBranch;
import com.fessc.develop.utils.BusiUtil;
import com.fessc.develop.utils.ExceptionUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BankCheckFileDownPushHandler {

    @Resource
    private List<ISendProcessor> bankCheckFileProcessors;

    private Map<String, ISendProcessor> processorMap;

    @PostConstruct
    public void init() {
        if (BusiUtil.isNotNull(bankCheckFileProcessors)) {
            processorMap = bankCheckFileProcessors.stream().collect(Collectors.toMap(ISendProcessor::getProcessorForBranch, p -> p, (v1, v2) -> v1));
        } else {
            processorMap = new HashMap<>();
        }
    }

    /**
     * 对账文件申请
     */
    public void bankCheckFileDownPush(List<BankCheckFileDownVo> bankCheckFileDownVoList, String pushType) {
        Map<String, List<BankCheckFileDownVo>> checkResultMap;
        checkResultMap = bankCheckFileDownVoList.stream().collect(Collectors.toMap(BankCheckFileDownVo::getBankId,
                p -> {
                    List<BankCheckFileDownVo> list = new ArrayList<>();
                    list.add(p);
                    return list;
                },
                (List<BankCheckFileDownVo> k1, List<BankCheckFileDownVo> k2) -> {
                    k1.addAll(k2);
                    return k1;
                }));

        //加工构造推送报文，调用接口推送
        preBankCheckFileDownPush(checkResultMap);

    }

    private void preBankCheckFileDownPush(Map<String, List<BankCheckFileDownVo>> bankCheckFileDownVoMap) {
        for (Map.Entry<String, List<BankCheckFileDownVo>> entry : bankCheckFileDownVoMap.entrySet()) {
            try {
                ISendProcessor processor = BusiUtil.isNull(processorMap.get(entry.getKey())) ? processorMap.get(EnumBranch.COMMON.toString()) : processorMap.get(entry.getKey());
                if (BusiUtil.isNull(processor)) {
                    throw ExceptionUtil.businessException("EE4001");
                }
                processor.bankCheckFileDownLoadProcess(entry.getValue()); //银行对账文件下载推送
            } catch (Exception e) {
                if (e instanceof BusinessException) {
                    log.error(((BusinessException) e).getResult().getMsg(), e);
                } else {
                    log.error(e.getMessage(), e);
                }
            }
        }
    }

}
